//
//  OMTPhotoCell.m
//  OMTImagePicker
//
//  Created by yizhaorong on 2017/11/15.
//

#import "OMTPhotoCell.h"
#import "UIImageView+OMTAsset.h"
#import "OMTAlbumManager.h"
#import "YYAnimatedImageView.h"

#import "OMTImagePickerController.h"

@interface OMTPhotoCell ()

@property (nonatomic, strong) YYAnimatedImageView *imageView;
// 数字视图
@property (nonatomic, strong) UIImageView *numberView;
// 数字
@property (nonatomic, strong) UILabel *numberLabel;
// GIF图标
@property (nonatomic, strong) UILabel *GIFLabel;
// 视频面板
@property (nonatomic, strong) UIView *videoPanel;
// 视频图标
@property (nonatomic, strong) UIImageView *videoIconView;
// 时间标签
@property (nonatomic, strong) UILabel *timeLabel;

@end

@implementation OMTPhotoCell

#pragma mark - Lifecycle

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self setupSubviews];
        [self setLayout];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(stateChangedNotification:) name:OMTAssetAssetSelectedStateChangedNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(assetTypeChangedNotification:) name:OMTAssetAssetTypeChangedNotification object:nil];
        
    }
    return self;
}

#pragma mark - View Lifecycle
- (void)setupSubviews {
    // 初始化子视图
    _imageView = [YYAnimatedImageView new];
    _imageView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    _imageView.clipsToBounds = YES;
    [self.contentView addSubview:_imageView];
    
    _numberView = [UIImageView new];
    _numberView.layer.borderColor = OMTAlbumRGB(0x38d5be).CGColor;
    _numberView.layer.borderWidth = 5;
    _numberView.hidden = YES;
    [self.contentView addSubview:_numberView];
    
    _numberLabel = [UILabel new];
    _numberLabel.textAlignment = NSTextAlignmentCenter;
    _numberLabel.backgroundColor = OMTAlbumRGB(0x38d5be);
    _numberLabel.font = [UIFont boldSystemFontOfSize:13];
    _numberLabel.layer.cornerRadius = 3;
    _numberLabel.layer.masksToBounds = YES;
    _numberLabel.textColor = [UIColor whiteColor];
    [_numberView addSubview:_numberLabel];
    
    _GIFLabel = [UILabel new];
    _GIFLabel.text = @"GIF";
    _GIFLabel.font = [UIFont systemFontOfSize:14];
    _GIFLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
    _GIFLabel.layer.cornerRadius = 3;
    _GIFLabel.layer.masksToBounds = YES;
    _GIFLabel.textAlignment = NSTextAlignmentCenter;
    _GIFLabel.textColor = [UIColor whiteColor];
    [_GIFLabel sizeToFit];
    [self.contentView addSubview:_GIFLabel];
    
    _videoPanel = [UIView new];
    _videoPanel.frame = CGRectMake(0, 0, 0, 23);
    _videoPanel.backgroundColor = OMTAlbumRGBA(0x000000, 0.5);
    _videoPanel.hidden = YES;
    [self.contentView addSubview:_videoPanel];
    
    _videoIconView = [UIImageView new];
    [_videoPanel addSubview:_videoIconView];
    
    _timeLabel = [UILabel new];
    _timeLabel.font = [UIFont boldSystemFontOfSize:11];
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.textAlignment = NSTextAlignmentCenter;
    [_videoPanel addSubview:_timeLabel];
    
    UILongPressGestureRecognizer *gesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(previewAction:)];
    [self.contentView addGestureRecognizer:gesture];
    
    if (omt_album_is_rtl_language()) {
        self.contentView.transform = CGAffineTransformMakeScale(-1, 1);
    }
}

- (void)setLayout {
    // 设置或更新布局
    CGFloat width = self.bounds.size.width;
    CGFloat height = self.bounds.size.height;
    
    self.imageView.frame = self.bounds;
    self.numberView.frame = self.bounds;
    
    CGFloat numberW = 30;
    CGFloat numberH = 30;
    CGFloat numberX = self.bounds.size.width - numberW;
    CGFloat numberY = 0;
    CGRect numberFrame = CGRectMake(numberX, numberY, numberW, numberH);
    self.numberLabel.frame = numberFrame;
    
    CGSize GIFSize = self.GIFLabel.bounds.size;
    CGFloat GIFX = width - 35;
    CGFloat GIFY = self.bounds.size.height - GIFSize.height - 5;
    CGRect GIFFrame = CGRectMake(GIFX, GIFY, 30, GIFSize.height);
    self.GIFLabel.frame = GIFFrame;
    
    CGRect videoPanelFrame = CGRectMake(0, height - 23, width, 23);
    self.videoPanel.frame = videoPanelFrame;
    
    CGSize timeSize = [self.timeLabel sizeThatFits:self.contentView.bounds.size];
    CGFloat timeW = timeSize.width;
    CGFloat timeH = timeSize.height;
    CGFloat timeX = width - timeW - 6;
    CGFloat timeY = (23 - timeH) / 2;
    CGRect timeFrame = CGRectMake(timeX, timeY, timeW, timeH);
    self.timeLabel.frame = timeFrame;
    
    CGRect videoIconFrame = self.videoIconView.frame;
    videoIconFrame.origin.x = 6;
    videoIconFrame.origin.y = (23 - videoIconFrame.size.height) / 2;
    self.videoIconView.frame = videoIconFrame;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self setLayout];
}
#pragma mark - Actions
- (void)previewAction:(UILongPressGestureRecognizer *)sender {
    if (!self.asset || UIGestureRecognizerStateBegan != sender.state) return;
    
    if ([self.delegate respondsToSelector:@selector(photoCellWillPreview:)]) {
        [self.delegate photoCellWillPreview:self];
    }
}

#pragma mark - Private
- (void)stateChangedNotification:(NSNotification *)notification {
    OMTAsset *asset = notification.object;
    if (!asset) return;
    [self changeNumber];
}

- (void)assetTypeChangedNotification:(NSNotification *)notification {
    OMTAsset *asset = notification.object;
    if (!asset || asset != self.asset) return;
    
    __weak typeof(self) weakSelf = self;
    [self.imageView omt_setImageWithAsset:self.asset placeholderImage:nil completion:^(UIImage *image, OMTAsset *asset) {
        typeof(weakSelf) strongSelf = weakSelf;
        if (!strongSelf) return;
        
        if (strongSelf.asset != asset) return;
        
        if ([strongSelf.delegate respondsToSelector:@selector(photoCellNeedReload:)]) {
            [strongSelf.delegate photoCellNeedReload:strongSelf];
        }
    }];
}

- (void)changeNumber {
    self.numberView.hidden = !self.asset.isSelected;
    OMTImagePickerBuilder *builder = self.albumManager.builder;
    if (builder.maxSelectCount > 1) {
        OMTAlbumManager *albumManager = self.albumManager;
        NSInteger index = [albumManager.selectedPhotos indexOfObject:self.asset];
        NSInteger number = 0;
        if (index != NSNotFound) {
            number = index + 1;
        }
        self.numberLabel.hidden = NO;
        self.numberLabel.text = [NSString stringWithFormat:@"%ld", number];
    } else {
        self.numberLabel.hidden = YES;
    }
    
    [self setLayout];
}

#pragma mark - Public


#pragma mark - Protocol conformance


#pragma mark - Lazyload


#pragma mark - Custom Accessors
//自定义 setter getter
- (void)setAsset:(OMTAsset *)asset {
    _asset = asset;
    self.imageView.image = nil;
    [self.imageView omt_setImageWithAsset:asset];
    self.GIFLabel.hidden = !asset.isGIF;
    self.videoPanel.hidden = asset.mediaType != OMTAssetMediaTypeVideo;
    self.timeLabel.text = asset.duration;
    [self changeNumber];
}

- (void)setImage:(UIImage *)image {
    self.asset = nil;
    self.imageView.image = image;
    [self changeNumber];
}

- (void)setAlbumManager:(OMTAlbumManager *)albumManager {
    _albumManager = albumManager;
    UIImage *(^AlbumImageNamed)(NSString *) = [albumManager.builder.imageWithNamed copy];
    _videoIconView.image = AlbumImageNamed(@"omt_video_icon");
    [_videoIconView sizeToFit];
}

- (UIImage *)image {
    return self.imageView.image;
}

@end
